[[...path]].page.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. import type { ReactNode } from 'react';
  2. import React, { useEffect } from 'react';
  3. import EventEmitter from 'events';
  4. import { isIPageInfoForEntity, isPopulated } from '@growi/core';
  5. import type {
  6. GroupType,
  7. IDataWithMeta, IPageInfoForEntity, IPagePopulatedToShowRevision,
  8. } from '@growi/core';
  9. import {
  10. isClient, pagePathUtils, pathUtils,
  11. } from '@growi/core/dist/utils';
  12. import { AcceptedUploadFileType } from '@growi/editor';
  13. import ExtensibleCustomError from 'extensible-custom-error';
  14. import type {
  15. GetServerSideProps, GetServerSidePropsContext,
  16. } from 'next';
  17. import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
  18. import dynamic from 'next/dynamic';
  19. import Head from 'next/head';
  20. import { useRouter } from 'next/router';
  21. import superjson from 'superjson';
  22. import { useEditorModeClassName } from '~/client/services/layout';
  23. import { PageView } from '~/components/Page/PageView';
  24. import { DrawioViewerScript } from '~/components/Script/DrawioViewerScript';
  25. import { SupportedAction, type SupportedActionType } from '~/interfaces/activity';
  26. import type { CrowiRequest } from '~/interfaces/crowi-request';
  27. import type { EditorConfig } from '~/interfaces/editor-settings';
  28. import type { IPageGrantData } from '~/interfaces/page';
  29. import type { RendererConfig } from '~/interfaces/services/renderer';
  30. import type { PageModel, PageDocument } from '~/server/models/page';
  31. import type { PageRedirectModel } from '~/server/models/page-redirect';
  32. import {
  33. useCurrentUser,
  34. useIsForbidden, useIsSharedUser,
  35. useIsEnabledStaleNotification, useIsIdenticalPath,
  36. useIsSearchServiceConfigured, useIsSearchServiceReachable, useDisableLinkSharing,
  37. useDefaultIndentSize, useIsIndentSizeForced,
  38. useIsAclEnabled, useIsSearchPage, useIsEnabledAttachTitleHeader,
  39. useCsrfToken, useIsSearchScopeChildrenAsDefault, useIsEnabledMarp, useCurrentPathname,
  40. useIsSlackConfigured, useRendererConfig, useGrowiCloudUri,
  41. useEditorConfig, useIsAllReplyShown, useIsContainerFluid, useIsNotCreatable,
  42. useIsUploadAllFileAllowed, useIsUploadEnabled,
  43. // useAcceptedUploadFileType,
  44. } from '~/stores/context';
  45. import { useEditingMarkdown } from '~/stores/editor';
  46. import {
  47. useSWRxCurrentPage, useSWRMUTxCurrentPage, useSWRxIsGrantNormalized, useCurrentPageId,
  48. useIsNotFound, useIsLatestRevision, useTemplateTagData, useTemplateBodyData,
  49. } from '~/stores/page';
  50. import { useRedirectFrom } from '~/stores/page-redirect';
  51. import { useRemoteRevisionId } from '~/stores/remote-latest-page';
  52. import { useSelectedGrant } from '~/stores/ui';
  53. import { useSetupGlobalSocket, useSetupGlobalSocketForPage } from '~/stores/websocket';
  54. import loggerFactory from '~/utils/logger';
  55. import { BasicLayout } from '../components/Layout/BasicLayout';
  56. import GrowiContextualSubNavigationSubstance from '../components/Navbar/GrowiContextualSubNavigation';
  57. import { DisplaySwitcher } from '../components/Page/DisplaySwitcher';
  58. import type { NextPageWithLayout } from './_app.page';
  59. import type { CommonProps } from './utils/commons';
  60. import {
  61. getNextI18NextConfig, getServerSideCommonProps, generateCustomTitleForPage, useInitSidebarConfig, skipSSR, addActivity,
  62. } from './utils/commons';
  63. declare global {
  64. // eslint-disable-next-line vars-on-top, no-var
  65. var globalEmitter: EventEmitter;
  66. }
  67. const GrowiPluginsActivator = dynamic(() => import('~/features/growi-plugin/client/components').then(mod => mod.GrowiPluginsActivator), { ssr: false });
  68. const DescendantsPageListModal = dynamic(() => import('../components/DescendantsPageListModal').then(mod => mod.DescendantsPageListModal), { ssr: false });
  69. const UnsavedAlertDialog = dynamic(() => import('../components/UnsavedAlertDialog'), { ssr: false });
  70. const DrawioModal = dynamic(() => import('../components/PageEditor/DrawioModal').then(mod => mod.DrawioModal), { ssr: false });
  71. const HandsontableModal = dynamic(() => import('../components/PageEditor/HandsontableModal').then(mod => mod.HandsontableModal), { ssr: false });
  72. const TemplateModal = dynamic(() => import('../components/TemplateModal').then(mod => mod.TemplateModal), { ssr: false });
  73. const LinkEditModal = dynamic(() => import('../components/PageEditor/LinkEditModal').then(mod => mod.LinkEditModal), { ssr: false });
  74. const PageStatusAlert = dynamic(() => import('../components/PageStatusAlert').then(mod => mod.PageStatusAlert), { ssr: false });
  75. const QuestionnaireModalManager = dynamic(() => import('~/features/questionnaire/client/components/QuestionnaireModalManager'), { ssr: false });
  76. const TagEditModal = dynamic(() => import('../components/PageTags/TagEditModal').then(mod => mod.TagEditModal), { ssr: false });
  77. const logger = loggerFactory('growi:pages:all');
  78. const {
  79. isPermalink: _isPermalink, isCreatablePage,
  80. } = pagePathUtils;
  81. const { removeHeadingSlash } = pathUtils;
  82. type IPageToShowRevisionWithMeta = IDataWithMeta<IPagePopulatedToShowRevision & PageDocument, IPageInfoForEntity>;
  83. type IPageToShowRevisionWithMetaSerialized = IDataWithMeta<string, string>;
  84. superjson.registerCustom<IPageToShowRevisionWithMeta, IPageToShowRevisionWithMetaSerialized>(
  85. {
  86. isApplicable: (v): v is IPageToShowRevisionWithMeta => {
  87. return v?.data != null
  88. && v?.data.toObject != null
  89. && v?.meta != null
  90. && isIPageInfoForEntity(v.meta);
  91. },
  92. serialize: (v) => {
  93. return {
  94. data: superjson.stringify(v.data.toObject()),
  95. meta: superjson.stringify(v.meta),
  96. };
  97. },
  98. deserialize: (v) => {
  99. return {
  100. data: superjson.parse(v.data),
  101. meta: v.meta != null ? superjson.parse(v.meta) : undefined,
  102. };
  103. },
  104. },
  105. 'IPageToShowRevisionWithMetaTransformer',
  106. );
  107. // GrowiContextualSubNavigation for NOT shared page
  108. type GrowiContextualSubNavigationProps = {
  109. isLinkSharingDisabled: boolean,
  110. }
  111. const GrowiContextualSubNavigation = (props: GrowiContextualSubNavigationProps): JSX.Element => {
  112. const { isLinkSharingDisabled } = props;
  113. const { data: currentPage } = useSWRxCurrentPage();
  114. return (
  115. <GrowiContextualSubNavigationSubstance currentPage={currentPage} isLinkSharingDisabled={isLinkSharingDisabled} />
  116. );
  117. };
  118. type Props = CommonProps & {
  119. pageWithMeta: IPageToShowRevisionWithMeta | null,
  120. // pageUser?: any,
  121. redirectFrom?: string;
  122. // shareLinkId?: string;
  123. isLatestRevision?: boolean,
  124. isIdenticalPathPage?: boolean,
  125. isForbidden: boolean,
  126. isNotFound: boolean,
  127. isNotCreatable: boolean,
  128. // isAbleToDeleteCompletely: boolean,
  129. templateTagData?: string[],
  130. templateBodyData?: string,
  131. isSearchServiceConfigured: boolean,
  132. isSearchServiceReachable: boolean,
  133. isSearchScopeChildrenAsDefault: boolean,
  134. isEnabledMarp: boolean,
  135. isSlackConfigured: boolean,
  136. // isMailerSetup: boolean,
  137. isAclEnabled: boolean,
  138. // hasSlackConfig: boolean,
  139. drawioUri: string | null,
  140. noCdn: string,
  141. // highlightJsStyle: string,
  142. isAllReplyShown: boolean,
  143. isContainerFluid: boolean,
  144. editorConfig: EditorConfig,
  145. isEnabledStaleNotification: boolean,
  146. isEnabledAttachTitleHeader: boolean,
  147. // isEnabledLinebreaks: boolean,
  148. // isEnabledLinebreaksInComments: boolean,
  149. adminPreferredIndentSize: number,
  150. isIndentSizeForced: boolean,
  151. disableLinkSharing: boolean,
  152. skipSSR: boolean,
  153. ssrMaxRevisionBodyLength: number,
  154. grantData?: IPageGrantData,
  155. rendererConfig: RendererConfig,
  156. };
  157. const Page: NextPageWithLayout<Props> = (props: Props) => {
  158. // register global EventEmitter
  159. if (isClient() && window.globalEmitter == null) {
  160. window.globalEmitter = new EventEmitter();
  161. }
  162. const router = useRouter();
  163. useCurrentUser(props.currentUser ?? null);
  164. // commons
  165. useEditorConfig(props.editorConfig);
  166. useCsrfToken(props.csrfToken);
  167. useGrowiCloudUri(props.growiCloudUri);
  168. // page
  169. useIsContainerFluid(props.isContainerFluid);
  170. // useOwnerOfCurrentPage(props.pageUser != null ? JSON.parse(props.pageUser) : null);
  171. useIsForbidden(props.isForbidden);
  172. useIsNotCreatable(props.isNotCreatable);
  173. useRedirectFrom(props.redirectFrom ?? null);
  174. useIsSharedUser(false); // this page cann't be routed for '/share'
  175. useIsIdenticalPath(props.isIdenticalPathPage ?? false);
  176. useIsEnabledStaleNotification(props.isEnabledStaleNotification);
  177. useIsSearchPage(false);
  178. useIsEnabledAttachTitleHeader(props.isEnabledAttachTitleHeader);
  179. useIsSearchServiceConfigured(props.isSearchServiceConfigured);
  180. useIsSearchServiceReachable(props.isSearchServiceReachable);
  181. useIsSearchScopeChildrenAsDefault(props.isSearchScopeChildrenAsDefault);
  182. useIsSlackConfigured(props.isSlackConfigured);
  183. // useIsMailerSetup(props.isMailerSetup);
  184. useIsAclEnabled(props.isAclEnabled);
  185. // useHasSlackConfig(props.hasSlackConfig);
  186. // useNoCdn(props.noCdn);
  187. useDefaultIndentSize(props.adminPreferredIndentSize);
  188. useIsIndentSizeForced(props.isIndentSizeForced);
  189. useDisableLinkSharing(props.disableLinkSharing);
  190. useRendererConfig(props.rendererConfig);
  191. useIsEnabledMarp(props.rendererConfig.isEnabledMarp);
  192. // useRendererSettings(props.rendererSettingsStr != null ? JSON.parse(props.rendererSettingsStr) : undefined);
  193. // useGrowiRendererConfig(props.growiRendererConfigStr != null ? JSON.parse(props.growiRendererConfigStr) : undefined);
  194. useIsAllReplyShown(props.isAllReplyShown);
  195. useIsUploadAllFileAllowed(props.editorConfig.upload.isUploadAllFileAllowed);
  196. useIsUploadEnabled(props.editorConfig.upload.isUploadEnabled);
  197. // useAcceptedUploadFileType(props.editorConfig.acceptedUploadFileType);
  198. const { pageWithMeta } = props;
  199. const pageId = pageWithMeta?.data._id;
  200. const revisionBody = pageWithMeta?.data.revision?.body;
  201. useCurrentPathname(props.currentPathname);
  202. const { data: currentPage } = useSWRxCurrentPage(pageWithMeta?.data ?? null); // store initial data
  203. const { trigger: mutateCurrentPage } = useSWRMUTxCurrentPage();
  204. const { mutate: mutateEditingMarkdown } = useEditingMarkdown();
  205. const { data: currentPageId, mutate: mutateCurrentPageId } = useCurrentPageId();
  206. const { mutate: mutateIsNotFound } = useIsNotFound();
  207. const { mutate: mutateIsLatestRevision } = useIsLatestRevision();
  208. const { data: grantData } = useSWRxIsGrantNormalized(pageId);
  209. const { mutate: mutateSelectedGrant } = useSelectedGrant();
  210. const { mutate: mutateRemoteRevisionId } = useRemoteRevisionId();
  211. const { mutate: mutateTemplateTagData } = useTemplateTagData();
  212. const { mutate: mutateTemplateBodyData } = useTemplateBodyData();
  213. useSetupGlobalSocket();
  214. useSetupGlobalSocketForPage(pageId);
  215. // Store initial data (When revisionBody is not SSR)
  216. useEffect(() => {
  217. if (!props.skipSSR) {
  218. return;
  219. }
  220. if (currentPageId != null && !props.isNotFound) {
  221. const mutatePageData = async() => {
  222. const pageData = await mutateCurrentPage();
  223. mutateEditingMarkdown(pageData?.revision.body);
  224. };
  225. // If skipSSR is true, use the API to retrieve page data.
  226. // Because pageWIthMeta does not contain revision.body
  227. mutatePageData();
  228. }
  229. }, [currentPageId, mutateCurrentPage, mutateEditingMarkdown, props.isNotFound, props.skipSSR]);
  230. // sync grant data
  231. useEffect(() => {
  232. const grantDataToApply = props.grantData ? props.grantData : grantData?.grantData.currentPageGrant;
  233. mutateSelectedGrant(grantDataToApply);
  234. }, [grantData?.grantData.currentPageGrant, mutateSelectedGrant, props.grantData]);
  235. // sync pathname by Shallow Routing https://nextjs.org/docs/routing/shallow-routing
  236. useEffect(() => {
  237. const decodedURI = decodeURI(window.location.pathname);
  238. if (isClient() && decodedURI !== props.currentPathname) {
  239. const { search, hash } = window.location;
  240. router.replace(`${props.currentPathname}${search}${hash}`, undefined, { shallow: true });
  241. }
  242. }, [props.currentPathname, router]);
  243. // initialize mutateEditingMarkdown only once per page
  244. // need to include useCurrentPathname not useCurrentPagePath
  245. useEffect(() => {
  246. if (props.currentPathname != null) {
  247. mutateEditingMarkdown(revisionBody);
  248. }
  249. }, [mutateEditingMarkdown, revisionBody, props.currentPathname]);
  250. useEffect(() => {
  251. mutateRemoteRevisionId(pageWithMeta?.data.revision?._id);
  252. }, [mutateRemoteRevisionId, pageWithMeta?.data.revision?._id]);
  253. useEffect(() => {
  254. mutateCurrentPageId(pageId ?? null);
  255. }, [mutateCurrentPageId, pageId]);
  256. useEffect(() => {
  257. mutateIsNotFound(props.isNotFound);
  258. }, [mutateIsNotFound, props.isNotFound]);
  259. useEffect(() => {
  260. mutateIsLatestRevision(props.isLatestRevision);
  261. }, [mutateIsLatestRevision, props.isLatestRevision]);
  262. useEffect(() => {
  263. mutateTemplateTagData(props.templateTagData);
  264. }, [props.templateTagData, mutateTemplateTagData]);
  265. useEffect(() => {
  266. mutateTemplateBodyData(props.templateBodyData);
  267. }, [props.templateBodyData, mutateTemplateBodyData]);
  268. // If the data on the page changes without router.push, pageWithMeta remains old because getServerSideProps() is not executed
  269. // So preferentially take page data from useSWRxCurrentPage
  270. const pagePath = currentPage?.path ?? pageWithMeta?.data.path ?? props.currentPathname;
  271. const title = generateCustomTitleForPage(props, pagePath);
  272. return (
  273. <>
  274. <Head>
  275. <title>{title}</title>
  276. </Head>
  277. <div className="dynamic-layout-root justify-content-between">
  278. <nav className="sticky-top">
  279. <GrowiContextualSubNavigation isLinkSharingDisabled={props.disableLinkSharing} />
  280. </nav>
  281. <DisplaySwitcher
  282. pageView={(
  283. <PageView
  284. pagePath={pagePath}
  285. initialPage={pageWithMeta?.data}
  286. rendererConfig={props.rendererConfig}
  287. />
  288. )}
  289. />
  290. <PageStatusAlert />
  291. </div>
  292. </>
  293. );
  294. };
  295. const BasicLayoutWithEditor = ({ children }: { children?: ReactNode }): JSX.Element => {
  296. const editorModeClassName = useEditorModeClassName();
  297. return <BasicLayout className={editorModeClassName}>{children}</BasicLayout>;
  298. };
  299. type LayoutProps = Props & {
  300. children?: ReactNode
  301. }
  302. const Layout = ({ children, ...props }: LayoutProps): JSX.Element => {
  303. // init sidebar config with UserUISettings and sidebarConfig
  304. useInitSidebarConfig(props.sidebarConfig, props.userUISettings);
  305. return <BasicLayoutWithEditor>{children}</BasicLayoutWithEditor>;
  306. };
  307. Page.getLayout = function getLayout(page: React.ReactElement<Props>) {
  308. return (
  309. <>
  310. <GrowiPluginsActivator />
  311. <DrawioViewerScript />
  312. <Layout {...page.props}>
  313. {page}
  314. </Layout>
  315. <UnsavedAlertDialog />
  316. <DescendantsPageListModal />
  317. <DrawioModal />
  318. <HandsontableModal />
  319. <QuestionnaireModalManager />
  320. <TemplateModal />
  321. <LinkEditModal />
  322. <TagEditModal />
  323. </>
  324. );
  325. };
  326. function getPageIdFromPathname(currentPathname: string): string | null {
  327. return _isPermalink(currentPathname) ? removeHeadingSlash(currentPathname) : null;
  328. }
  329. class MultiplePagesHitsError extends ExtensibleCustomError {
  330. pagePath: string;
  331. constructor(pagePath: string) {
  332. super(`MultiplePagesHitsError occured by '${pagePath}'`);
  333. this.pagePath = pagePath;
  334. }
  335. }
  336. async function injectPageData(context: GetServerSidePropsContext, props: Props): Promise<void> {
  337. const { model: mongooseModel } = await import('mongoose');
  338. const req: CrowiRequest = context.req as CrowiRequest;
  339. const { crowi } = req;
  340. const { revisionId } = req.query;
  341. const Page = crowi.model('Page') as PageModel;
  342. const PageRedirect = mongooseModel('PageRedirect') as PageRedirectModel;
  343. const { pageService, configManager, pageGrantService } = crowi;
  344. let currentPathname = props.currentPathname;
  345. const pageId = getPageIdFromPathname(currentPathname);
  346. const isPermalink = _isPermalink(currentPathname);
  347. const { user } = req;
  348. if (!isPermalink) {
  349. // check redirects
  350. const chains = await PageRedirect.retrievePageRedirectEndpoints(currentPathname);
  351. if (chains != null) {
  352. // overwrite currentPathname
  353. currentPathname = chains.end.toPath;
  354. props.currentPathname = currentPathname;
  355. // set redirectFrom
  356. props.redirectFrom = chains.start.fromPath;
  357. }
  358. // check whether the specified page path hits to multiple pages
  359. const count = await Page.countByPathAndViewer(currentPathname, user, null, true);
  360. if (count > 1) {
  361. throw new MultiplePagesHitsError(currentPathname);
  362. }
  363. }
  364. const pageWithMeta: IPageToShowRevisionWithMeta | null = await pageService.findPageAndMetaDataByViewer(pageId, currentPathname, user, true); // includeEmpty = true, isSharedPage = false
  365. const page = pageWithMeta?.data as unknown as PageDocument;
  366. // add user to seen users
  367. if (page != null && user != null) {
  368. await page.seen(user);
  369. }
  370. // populate & check if the revision is latest
  371. if (page != null) {
  372. page.initLatestRevisionField(revisionId);
  373. props.isLatestRevision = page.isLatestRevision();
  374. const ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  375. props.skipSSR = await skipSSR(page, ssrMaxRevisionBodyLength);
  376. await page.populateDataToShowRevision(props.skipSSR); // shouldExcludeBody = skipSSR
  377. }
  378. if (page == null && user != null) {
  379. const templateData = await Page.findTemplate(props.currentPathname);
  380. if (templateData != null) {
  381. props.templateTagData = templateData.templateTags as string[];
  382. props.templateBodyData = templateData.templateBody as string;
  383. }
  384. // apply parent page grant, without groups that user isn't related to
  385. const ancestor = await Page.findAncestorByPathAndViewer(currentPathname, user);
  386. if (ancestor != null) {
  387. ancestor.populate('grantedGroups.item');
  388. const userRelatedGrantedGroups = (await pageGrantService.getUserRelatedGrantedGroups(ancestor, user)).map((group) => {
  389. if (isPopulated(group.item)) {
  390. return {
  391. id: group.item._id,
  392. name: group.item.name,
  393. type: group.type,
  394. };
  395. }
  396. return null;
  397. }).filter((info): info is NonNullable<{id: string, name: string, type: GroupType}> => info != null);
  398. props.grantData = {
  399. grant: ancestor.grant,
  400. userRelatedGrantedGroups,
  401. };
  402. }
  403. }
  404. props.pageWithMeta = pageWithMeta;
  405. }
  406. async function injectRoutingInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  407. const req: CrowiRequest = context.req as CrowiRequest;
  408. const { crowi } = req;
  409. const Page = crowi.model('Page') as PageModel;
  410. const { currentPathname } = props;
  411. const pageId = getPageIdFromPathname(currentPathname);
  412. const isPermalink = _isPermalink(currentPathname);
  413. const page = props.pageWithMeta?.data;
  414. if (props.isIdenticalPathPage) {
  415. props.isNotCreatable = true;
  416. }
  417. else if (page == null) {
  418. props.isNotFound = true;
  419. props.isNotCreatable = !isCreatablePage(currentPathname);
  420. // check the page is forbidden or just does not exist.
  421. const count = isPermalink ? await Page.count({ _id: pageId }) : await Page.count({ path: currentPathname });
  422. props.isForbidden = count > 0;
  423. }
  424. else {
  425. props.isNotFound = page.isEmpty;
  426. props.isNotCreatable = false;
  427. props.isForbidden = false;
  428. // /62a88db47fed8b2d94f30000 ==> /path/to/page
  429. if (isPermalink && page.isEmpty) {
  430. props.currentPathname = page.path;
  431. }
  432. // /path/to/page ==> /62a88db47fed8b2d94f30000
  433. if (!isPermalink && !page.isEmpty) {
  434. const isToppage = pagePathUtils.isTopPage(props.currentPathname);
  435. if (!isToppage) {
  436. props.currentPathname = `/${page._id}`;
  437. }
  438. }
  439. }
  440. }
  441. // async function injectPageUserInformation(context: GetServerSidePropsContext, props: Props): Promise<void> {
  442. // const req: CrowiRequest = context.req as CrowiRequest;
  443. // const { crowi } = req;
  444. // const UserModel = crowi.model('User');
  445. // if (isUserPage(props.currentPagePath)) {
  446. // const user = await UserModel.findUserByUsername(UserModel.getUsernameByPath(props.currentPagePath));
  447. // if (user != null) {
  448. // props.pageUser = JSON.stringify(user.toObject());
  449. // }
  450. // }
  451. // }
  452. function injectServerConfigurations(context: GetServerSidePropsContext, props: Props): void {
  453. const req: CrowiRequest = context.req as CrowiRequest;
  454. const { crowi } = req;
  455. const {
  456. searchService, configManager, aclService,
  457. } = crowi;
  458. props.isSearchServiceConfigured = searchService.isConfigured;
  459. props.isSearchServiceReachable = searchService.isReachable;
  460. props.isSearchScopeChildrenAsDefault = configManager.getConfig('crowi', 'customize:isSearchScopeChildrenAsDefault');
  461. props.isSlackConfigured = crowi.slackIntegrationService.isSlackConfigured;
  462. // props.isMailerSetup = mailService.isMailerSetup;
  463. props.isAclEnabled = aclService.isAclEnabled();
  464. // props.hasSlackConfig = slackNotificationService.hasSlackConfig();
  465. props.drawioUri = configManager.getConfig('crowi', 'app:drawioUri');
  466. props.noCdn = configManager.getConfig('crowi', 'app:noCdn');
  467. // props.highlightJsStyle = configManager.getConfig('crowi', 'customize:highlightJsStyle');
  468. props.isAllReplyShown = configManager.getConfig('crowi', 'customize:isAllReplyShown');
  469. props.isContainerFluid = configManager.getConfig('crowi', 'customize:isContainerFluid');
  470. props.isEnabledStaleNotification = configManager.getConfig('crowi', 'customize:isEnabledStaleNotification');
  471. props.disableLinkSharing = configManager.getConfig('crowi', 'security:disableLinkSharing');
  472. props.editorConfig = {
  473. upload: {
  474. isUploadAllFileAllowed: crowi.fileUploadService.getFileUploadEnabled(),
  475. isUploadEnabled: crowi.fileUploadService.getIsUploadable(),
  476. },
  477. // acceptedUploadFileType: (() => {
  478. // if (!crowi.fileUploadService.getIsUploadable()) {
  479. // return AcceptedUploadFileType.NONE;
  480. // }
  481. // if (crowi.fileUploadService.getFileUploadEnabled()) {
  482. // return AcceptedUploadFileType.ALL;
  483. // }
  484. // return AcceptedUploadFileType.IMAGE;
  485. // })(),
  486. };
  487. props.adminPreferredIndentSize = configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize');
  488. props.isIndentSizeForced = configManager.getConfig('markdown', 'markdown:isIndentSizeForced');
  489. props.isEnabledAttachTitleHeader = configManager.getConfig('crowi', 'customize:isEnabledAttachTitleHeader');
  490. props.rendererConfig = {
  491. isEnabledLinebreaks: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaks'),
  492. isEnabledLinebreaksInComments: configManager.getConfig('markdown', 'markdown:isEnabledLinebreaksInComments'),
  493. isEnabledMarp: configManager.getConfig('crowi', 'customize:isEnabledMarp'),
  494. adminPreferredIndentSize: configManager.getConfig('markdown', 'markdown:adminPreferredIndentSize'),
  495. isIndentSizeForced: configManager.getConfig('markdown', 'markdown:isIndentSizeForced'),
  496. drawioUri: configManager.getConfig('crowi', 'app:drawioUri'),
  497. plantumlUri: configManager.getConfig('crowi', 'app:plantumlUri'),
  498. // XSS Options
  499. isEnabledXssPrevention: configManager.getConfig('markdown', 'markdown:rehypeSanitize:isEnabledPrevention'),
  500. xssOption: configManager.getConfig('markdown', 'markdown:rehypeSanitize:option'),
  501. attrWhitelist: JSON.parse(crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:attributes')),
  502. tagWhitelist: crowi.configManager.getConfig('markdown', 'markdown:rehypeSanitize:tagNames'),
  503. highlightJsStyleBorder: crowi.configManager.getConfig('crowi', 'customize:highlightJsStyleBorder'),
  504. };
  505. props.ssrMaxRevisionBodyLength = configManager.getConfig('crowi', 'app:ssrMaxRevisionBodyLength');
  506. }
  507. /**
  508. * for Server Side Translations
  509. * @param context
  510. * @param props
  511. * @param namespacesRequired
  512. */
  513. async function injectNextI18NextConfigurations(context: GetServerSidePropsContext, props: Props, namespacesRequired?: string[] | undefined): Promise<void> {
  514. const nextI18NextConfig = await getNextI18NextConfig(serverSideTranslations, context, namespacesRequired);
  515. props._nextI18Next = nextI18NextConfig._nextI18Next;
  516. }
  517. const getAction = (props: Props): SupportedActionType => {
  518. if (props.isNotCreatable) {
  519. return SupportedAction.ACTION_PAGE_NOT_CREATABLE;
  520. }
  521. if (props.isForbidden) {
  522. return SupportedAction.ACTION_PAGE_FORBIDDEN;
  523. }
  524. if (props.isNotFound) {
  525. return SupportedAction.ACTION_PAGE_NOT_FOUND;
  526. }
  527. if (pagePathUtils.isUsersHomepage(props.pageWithMeta?.data.path ?? '')) {
  528. return SupportedAction.ACTION_PAGE_USER_HOME_VIEW;
  529. }
  530. return SupportedAction.ACTION_PAGE_VIEW;
  531. };
  532. export const getServerSideProps: GetServerSideProps = async(context: GetServerSidePropsContext) => {
  533. const req = context.req as CrowiRequest;
  534. const { user } = req;
  535. const result = await getServerSideCommonProps(context);
  536. // check for presence
  537. // see: https://github.com/vercel/next.js/issues/19271#issuecomment-730006862
  538. if (!('props' in result)) {
  539. throw new Error('invalid getSSP result');
  540. }
  541. const props: Props = result.props as Props;
  542. if (props.redirectDestination != null) {
  543. return {
  544. redirect: {
  545. permanent: false,
  546. destination: props.redirectDestination,
  547. },
  548. };
  549. }
  550. if (user != null) {
  551. props.currentUser = user.toObject();
  552. }
  553. try {
  554. await injectPageData(context, props);
  555. }
  556. catch (err) {
  557. if (err instanceof MultiplePagesHitsError) {
  558. props.isIdenticalPathPage = true;
  559. }
  560. else {
  561. throw err;
  562. }
  563. }
  564. await injectRoutingInformation(context, props);
  565. injectServerConfigurations(context, props);
  566. await injectNextI18NextConfigurations(context, props, ['translation']);
  567. addActivity(context, getAction(props));
  568. return {
  569. props,
  570. };
  571. };
  572. export default Page;